<?php
class DigUser_Library_Acl extends Zend_Acl
{
   
    public function addRoles(array $roles) 
    {
        foreach ($roles as $role => $extends) {
            if(empty($extends)) {$extends = null;}
            if($extends == 'superuser') {
                $this->addRole($role);
                parent::allow($role);
            } else {
                $this->addRole($role, $extends);
            }
        }
    }
    
    public function addResource($module, $controller = null, $action = null)
    {
        $resourceId = $this->_getResourceId($module, $controller, $action);
        if(! $this->has($resourceId)) {
            return parent::addResource(new Zend_Acl_Resource($resourceId));
        }
    }
    
    public function allow($role, $module, $controller = null, $action = null)
    {
        $resourceId = $this->_getResourceId($module, $controller, $action);
        return parent::allow($role, $resourceId);
    }

    public function deny($role, $module, $controller = null, $action = null)
    {
        $resourceId = $this->_getResourceId($module, $controller, $action);
        return parent::deny($role, $resourceId);
    }


    
    public function isAllowed($role, $module, $controller = null, $action = null)
    {
        //Zend_Debug::dump(func_get_args());
        $moduleResource = $this->_getResourceId($module);
        $controllerResource = $this->_getResourceId($module, $controller);
        $actionResource = $this->_getResourceId($module, $controller, $action);
        if($this->has($actionResource)) {
            return parent::isAllowed($role, $actionResource);
        } elseif ($this->has($controllerResource)) {
            return parent::isAllowed($role, $controllerResource);
        } else {
            return parent::isAllowed($role, $moduleResource);
        }
    }
    
    public function urlIsAllowed($role, $url)
    {
        $urlParts = explode('/', $url);
        if(is_array($urlParts)) {
            if(empty($urlParts[0])) {
                array_shift($urlParts);
            }
            $module = (!empty($urlParts[0])) ? $urlParts[0] : 'default';
            $controller = (!empty($urlParts[1])) ? $urlParts[1] : null;
            $action = (!empty($urlParts[2])) ? $urlParts[2] : null;
        } else {
            $module = 'default';
            $controller = null;
            $action = null;
        }
        return $this->isAllowed($role, $module, $controller, $action);
    }
    
    protected function _getResourceId($module, $controller = null, $action = null)
    {
        $resourceId = $module;
        if($controller != null) {
            $resourceId .= '_' . $controller;
            if($action != null) {
                $resourceId .= '_' . $action;
            }
        }
        return $resourceId;
    }
}
?>